package com.ypj.rpc.utils;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.ypj.rpc.enumeration.RpcError;
import com.ypj.rpc.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.rmi.Naming;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Nacos工具类负责管理Nacos连接等功能
 */
@Slf4j
public class NacosUtils {

    private static final NamingService NAMING_SERVICE;

    private static final Set<String> serviceNames=new HashSet<>();
    private static InetSocketAddress address;

    private static final String SERVER_ADDR="127.0.0.1:8848";

    static {
        NAMING_SERVICE=getNacosNamingService();
    }
    public static NamingService getNacosNamingService() {
        try {
            return NamingFactory.createNamingService(SERVER_ADDR);
        } catch (NacosException e) {
            log.error("连接到Nacos时有错误发生: ", e);
            throw new RpcException(RpcError.FAILED_TO_CONNECT_TO_SERVICE_REGISTRY.getMessage());
        }
    }

    public static void registerService(String serviceName,InetSocketAddress inetSocketAddress) throws NacosException {
        NacosUtils.address=inetSocketAddress;
        //在Nacos上注册服务：服务名，服务提供者的地址
        NAMING_SERVICE.registerInstance(serviceName,inetSocketAddress.getHostName(),inetSocketAddress.getPort());
        serviceNames.add(serviceName);
    }


    public static List<Instance> getAllInstance(String serviceName) throws NacosException {
        return NAMING_SERVICE.getAllInstances(serviceName);
    }

    public static void clearRegistry(){
        if (!serviceNames.isEmpty()&&address!=null){
            log.info("正在注销服务...");
            Iterator<String> iterator = serviceNames.iterator();
            while(iterator.hasNext()){
                String serviceName=iterator.next();
                try {
                    NAMING_SERVICE.deregisterInstance(serviceName,address.getHostName(),address.getPort());
                } catch (NacosException e) {
                    log.error("注销：{}失败",serviceName,e);
                }
            }
        }
        log.info("注销成功！");
    }
}
